<?php

namespace App\Exports;

use App\Models\Rbac\GuardUser;
use App\Models\Rbac\GuardUserPrice;
use Maatwebsite\Excel\Concerns\FromArray;
use PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder;

class CountPriceExport extends DefaultValueBinder implements FromArray
{
    private $conditions;

    public function __construct(array $conditions) {
        $this->conditions = $conditions;
    }

    public function array():array  {
        $data = [
            [
                'ID',
                '日期',
                '渠道',
                '当日新增-服务车辆',
                '当日新增-保费总额',
                '当日新增-服务费总额',
                '累计-服务车辆',
                '累计-保费总额',
                '累计-服务费总额',
                '已满期利润额',
                '更新时间',
                '创建时间',
            ]
        ];



        $records = (new GuardUserPrice())->getLst($this->conditions)->with('getGuardUser')->get();
        foreach ($records as &$record) {
            $record->account = $record->getGuardUser->name;
            unset($record->getGuardUser);
            $data[] = $record->toArray();
        }

        //合计
        $date = $this->conditions['date']??[date('Y-m-d'),date('Y-m-d')];
        $sum_day_car_count = GuardUserPrice::whereBetween('date',$date)->sum('day_car_count');
        $sum_day_bao_price = GuardUserPrice::whereBetween('date',$date)->sum('day_bao_price');
        $sum_day_service_price = GuardUserPrice::whereBetween('date',$date)->sum('day_service_price');

        $sum_ins_car_count = 0;
        $sum_ins_bao_price = 0;
        $sum_ins_service_price = 0;

        $sum_full_price = 0;

        $guardUsers = GuardUser::get();

        foreach ($guardUsers as $guardUser) {

            $temp =  GuardUserPrice::where('account',$guardUser->id)->where('date',$date[1])->first();

            if(!empty($temp)){
                $sum_ins_car_count += $temp->ins_car_count;
                $sum_ins_bao_price += $temp->ins_bao_price;
                $sum_ins_service_price += $temp->ins_service_price;
                $sum_full_price += $temp->full_price;
            }
        }

        $msg = "合计：当日服务车辆 $sum_day_car_count ，当日服务保费 $sum_day_bao_price ，当日服务费 $sum_day_service_price ，累计服务车辆 $sum_ins_car_count ，累计保费 $sum_ins_bao_price ，累计服务费 $sum_ins_service_price ，已满期利润额 $sum_full_price";
        array_unshift($data,[$msg]);
        return $data;
    }

}
